package com.gzc.just.play.last.war.robotclient.handler;

import com.gzc.just.play.last.war.common.annotation.MessageHandler;
import com.gzc.just.play.last.war.common.handler.SimpleMessageHandler;
import com.gzc.just.play.last.war.protobuf.ls.lstogc.LSToGC;
import com.gzc.just.play.last.war.robotclient.NettyRobotClient;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@MessageHandler(serverTypes = MessageHandler.ServerType.ROBOT_CLIENT)
public class BSAddrResponseHandler implements SimpleMessageHandler {
    private static final Logger log = LoggerFactory.getLogger(BSAddrResponseHandler.class);

    @Override
    public void handle(Object message, ChannelHandlerContext ctx) throws Exception {
        LSToGC.ServerBSAddr bsAddr = null;
        if (message instanceof byte[]) {
            bsAddr = LSToGC.ServerBSAddr.parseFrom((byte[]) message);
        } else if (message instanceof LSToGC.ServerBSAddr) {
            bsAddr = (LSToGC.ServerBSAddr) message;
        }

        NettyRobotClient client = ctx.channel().attr(NettyRobotClient.CLIENT_KEY).get();
        if (client == null) {
            log.warn("BSAddrResponseHandler: Robot client not found in channel attributes");
            return;
        }

        if (bsAddr != null && bsAddr.getServerinfoCount() > 0) {
            LSToGC.ServerInfo info = bsAddr.getServerinfo(0);
            log.info("Robot {} received BS address: {}:{}", client.getRobotId(), info.getServerAddr(), info.getServerPort());
            
            client.connectToBalanceServer(info.getServerAddr(), info.getServerPort());
        }
    }

    @Override
    public int getMessageId() {
        return 513;
    }

    @Override
    public String getName() {
        return "BSAddrResponseHandler";
    }

    @Override
    public Logger getLogger() {
        return log;
    }
}
